<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧tab栏 -->
      <el-form ref="addFormRef" :rules="addFormRules" :model="addForm"  label-width="100px" label-position="top">
        <el-tabs tab-position="left"  v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="name">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals1">
                <el-checkbox :label="item" v-for="(item, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyDataList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片的dialog -->
    <el-dialog :visible.sync="imgDialogVisible">
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created () {
    // 获取数据
    this.getCateList()
  },
  data () {
    return {
      // 步骤条当前激活数据
      activeIndex: '0',
      // 存储表单数据的对象
      addForm: {
        goods_name: '', // 商品名称
        goods_price: 0, // 商品价格
        goods_weight: 0, // 商品重量
        goods_number: 0, // 商品数量
        goods_cat: [], // 分类列表
        pics: [], // 存储用户选择的图片信息对象
        goods_introduce: '', // 文本编辑器的数据
        attrs: [] // 存储动态参数和静态属性数组中的值
      },
      // 存储用户获取商品分类数据
      cateList: [],
      // 验证规则对象
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数数组
      manyTabData: [],
      // 静态数组的存储数据
      onlyDataList: [],
      // 图片文件的上传路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片添加请求头token字段
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制预览图片dialog显示与隐藏
      imgDialogVisible: false,
      // 预览图片的路径
      previewPath: ''
    }
  },
  methods: {
    // 获取商品分类数据列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      // 判断用户获取数据成功与否
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败')
      this.cateList = res.data
      this.$message.success('获取商品分类数据成功')
    },
    // 级联选择器改变事件
    handleChange () {
      // 控制级联选择器的选择范围
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 监听tabs页切换事件
    beforeTabLeave (activeName, oldActiveName) {
      // 判断是否可以前往下一个标签页
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // tab被选中的点击事件
    async tabClicked () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        // 判断数据是否获取成功
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
        this.$message.success('获取商品参数成功')
        res.data.forEach(item => {
          // 新增一个空数组，存储用户选择的参数复选框
          item.attr_vals1 = []
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
        this.$message.success('获取商品参数成功')
        this.onlyDataList = res.data
      }
    },
    // 预览图片处理函数
    handlePreview (res) {
      // console.log(res)
      // 存储图片url路径
      this.previewPath = res.url
      // 显示图片预览对话框
      this.imgDialogVisible = true
    },
    // 图片删除函数
    handleRemove (res) {
      // console.log(respose)
      // 获取当前要删除的图片在数组中的索引值
      const index = this.addForm.pics.findIndex(item => {
        return item.pic === res.response.data.tmp_path
      })
      // console.log(index)
      // 删除图片
      this.addForm.pics.splice(index, 1)
    },
    // 图片上传成功
    handleSuccess (response) {
      // console.log(response)
      // 拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 将图片信息对象存储到数组中
      this.addForm.pics.push(picInfo)
    },
    // 添加商品按钮的点击事件
    addGoods () {
      // 预校验表单数据
      this.$refs.addFormRef.validate(async item => {
        if (!item) return
        // 校验成功，处理数据，发起请求
        // 请求的goods_cat字段需要数组，所以要将addForm表单中的goods_cat数组转换为字符串
        // 但是goods_cat数组和级联选择器绑定这里转换为数组，级联选择器会报错
        // 所以需要用深拷贝，先拷贝一个数组，再转换为字符串
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(this.addForm.goods_cat)
        // 处理动态参数
        // console.log(this.manyTabData)
        this.manyTabData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals1.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyDataList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 添加商品成功
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 5px 10px 5px 0 !important;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 20px;
}
</style>
